package com.wzs.setting.web.controller;

import com.wzs.setting.domain.Like;
import com.wzs.setting.domain.Readr;
import com.wzs.setting.service.ReaderService;
import com.wzs.utils.MD5Util;
import com.wzs.utils.PrintJson;
import com.wzs.vo.PaginationVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/reader/")
public class readerController {

    @Resource
    private ReaderService readerService;

    @RequestMapping("login.do")
    public void Login(HttpServletResponse response, HttpServletRequest request,
                      String username, String password) {
        System.out.println("执行读者登录验证操作");

        //将密码的明文形式转换成MD5的密文形式
        password = MD5Util.getMD5(password);
        try {
            Readr readr = readerService.login(username, password);
            request.getSession().setAttribute("SESSION_USER", readr);

            PrintJson.printJsonFlag(response, true);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            Map<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("msg", msg);

            PrintJson.printJsonObj(response, map);
        }
    }

    @RequestMapping("register.do")
    public void Register(HttpServletResponse response, Readr readr) {
        System.out.println("执行读者注册操作");
        boolean flag = readerService.register(readr);
        PrintJson.printJsonObj(response, flag);
    }

    @RequestMapping("loginOut.do")
    public String LoginOut(HttpServletRequest request){

        request.getSession().removeAttribute("SESSION_USER");

        return "redirect:/index.html";
    }

    @RequestMapping("like.do")
    @ResponseBody
    public boolean like(String novelId,String readerId){

        return readerService.like(novelId,readerId);

    }

    @ResponseBody
    @RequestMapping("pageList.do")
    public PaginationVO<Like> PageList(@RequestParam("pageNo") String pageNoStr,
                                       @RequestParam("pageSize") String pageSizeStr,
                                       String readrId) {
        int pageNo = Integer.parseInt(pageNoStr);
        int pageSize = Integer.parseInt(pageSizeStr);
        //计算出略过的记录数
        int skipCount = (pageNo - 1) * pageSize;
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageSize", pageSize);
        map.put("skipCount", skipCount);
        map.put("readrId", readrId);
        return readerService.pageList(map);
    }


}


















